package _18_剑指OfferII;

import java.util.Stack;

public class _036_剑指OfferII后缀表达式 {

    // 由于存放的数据是int类型，所以可以使用数组模拟栈结构
    public int evalRPN(String[] tokens) {
        int index = -1;
        int[] stack = new int[tokens.length];
        for (String token : tokens) {
            switch (token) {
                case "+":
                    stack[--index] += stack[index + 1];
                    break;
                case "-":
                    stack[--index] -= stack[index + 1];
                    break;
                case "*":
                    stack[--index] *= stack[index + 1];
                    break;
                case "/":
                    stack[--index] /= stack[index + 1];
                    break;
                default:
                    stack[++index] = Integer.parseInt(token);
            }
        }
        return stack[index];
    }

    public int evalRPN1(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (token.equals("*") ||
                    token.equals("/") ||
                    token.equals("+") ||
                    token.equals("-")) {
                Integer last = stack.pop();
                Integer first = stack.pop();
                switch (token) {
                    case "+":
                        last = first + last;
                        break;
                    case "-":
                        last = first - last;
                        break;
                    case "*":
                        last = first * last;
                        break;
                    case "/":
                        last = first / last;
                        break;
                }
                stack.push(last);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

}
